<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/xiehuan.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/xiehuan.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="AbstractApplicationContext 的refresh方法">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring IOC">
<meta property="og:url" content="http://yoursite.com/2019/11/14/Spring-IOC/index.html">
<meta property="og:site_name" content="xiehuan">
<meta property="og:description" content="AbstractApplicationContext 的refresh方法">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-11-18T11:55:51.523Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring IOC">
<meta name="twitter:description" content="AbstractApplicationContext 的refresh方法">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/11/14/Spring-IOC/"/>





  <title>Spring IOC | xiehuan</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiehuan</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/11/14/Spring-IOC/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiehuan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiehuan">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring IOC</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-11-14T22:43:43+08:00">
                2019-11-14
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>AbstractApplicationContext 的refresh方法<br><a id="more"></a></p>
<h2 id="refresh"><a href="#refresh" class="headerlink" title="refresh()"></a>refresh()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void refresh() throws BeansException, IllegalStateException &#123;</span><br><span class="line">	synchronized (this.startupShutdownMonitor) &#123;</span><br><span class="line">		// Prepare this context for refreshing.</span><br><span class="line">		prepareRefresh();</span><br><span class="line"></span><br><span class="line">		// Tell the subclass to refresh the internal bean factory.</span><br><span class="line">		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">		// Prepare the bean factory for use in this context.</span><br><span class="line">		prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">		try &#123;</span><br><span class="line">			// Allows post-processing of the bean factory in context subclasses.</span><br><span class="line">			postProcessBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">			// Invoke factory processors registered as beans in the context.</span><br><span class="line">			invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">			// Register bean processors that intercept bean creation.</span><br><span class="line">			registerBeanPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">			// Initialize message source for this context.</span><br><span class="line">			initMessageSource();</span><br><span class="line"></span><br><span class="line">			// Initialize event multicaster for this context.</span><br><span class="line">			initApplicationEventMulticaster();</span><br><span class="line"></span><br><span class="line">			// Initialize other special beans in specific context subclasses.</span><br><span class="line">			onRefresh();</span><br><span class="line"></span><br><span class="line">			// Check for listener beans and register them.</span><br><span class="line">			registerListeners();</span><br><span class="line"></span><br><span class="line">			// Instantiate all remaining (non-lazy-init) singletons.</span><br><span class="line">			finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">			// Last step: publish corresponding event.</span><br><span class="line">			finishRefresh();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		catch (BeansException ex) &#123;</span><br><span class="line">			if (logger.isWarnEnabled()) &#123;</span><br><span class="line">				logger.warn(&quot;Exception encountered during context initialization - &quot; +</span><br><span class="line">						&quot;cancelling refresh attempt: &quot; + ex);</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			// Destroy already created singletons to avoid dangling resources.</span><br><span class="line">			destroyBeans();</span><br><span class="line"></span><br><span class="line">			// Reset &apos;active&apos; flag.</span><br><span class="line">			cancelRefresh(ex);</span><br><span class="line"></span><br><span class="line">			// Propagate exception to caller.</span><br><span class="line">			throw ex;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		finally &#123;</span><br><span class="line">			// Reset common introspection caches in Spring&apos;s core, since we</span><br><span class="line">			// might not ever need metadata for singleton beans anymore...</span><br><span class="line">			resetCommonCaches();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="prepareRefresh"><a href="#prepareRefresh" class="headerlink" title="prepareRefresh()"></a>prepareRefresh()</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">protected void prepareRefresh() &#123;</span><br><span class="line">	//</span><br><span class="line">	this.startupDate = System.currentTimeMillis();</span><br><span class="line">	//context是否关闭的标志，设置为false</span><br><span class="line">	this.closed.set(false);</span><br><span class="line">	//ontext是否激活的标志，设置为true</span><br><span class="line">	this.active.set(true);</span><br><span class="line"></span><br><span class="line">	if (logger.isInfoEnabled()) &#123;</span><br><span class="line">		logger.info(&quot;Refreshing &quot; + this);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	// 在上下文环境中初始化任何占位符属性源()</span><br><span class="line">	//际上AbstractApplicationContext类中的initPropertySources都是为空的 在它的子类中</span><br><span class="line">    //才去做真正的加载资源操作 调用的是WebApplicationContextUtils.initServletPropertySources方法</span><br><span class="line">	initPropertySources();</span><br><span class="line"></span><br><span class="line">	// 验证标记为所需的所有属性都是可解析的</span><br><span class="line">	// 查看 ConfigurablePropertyResolver#setRequiredProperties</span><br><span class="line">	//ConfigurablePropertyResolver 只是一个接口类，具体完成验证功能的是它的实现类：AbstractPropertyResolver</span><br><span class="line">	//在validateRequiredProperties方法中，会去验证requiredProperties对应的key是否存在对应的环境变量，如果不存在就报错</span><br><span class="line">	getEnvironment().validateRequiredProperties();</span><br><span class="line"></span><br><span class="line">	// 储存监听器</span><br><span class="line">	if (this.earlyApplicationListeners == null) &#123;</span><br><span class="line">		this.earlyApplicationListeners = new LinkedHashSet&lt;&gt;(this.applicationListeners);</span><br><span class="line">	&#125;</span><br><span class="line">	else &#123;</span><br><span class="line">		// 重置监听器</span><br><span class="line">		this.applicationListeners.clear();</span><br><span class="line">		this.applicationListeners.addAll(this.earlyApplicationListeners);</span><br><span class="line">	&#125;</span><br><span class="line">	// 有留给子类扩展的位置，用来将属性加入到applicationContext中</span><br><span class="line">	this.earlyApplicationEvents = new LinkedHashSet&lt;ApplicationEvent&gt;();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="initPropertySources"><a href="#initPropertySources" class="headerlink" title="initPropertySources()"></a>initPropertySources()</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">/** </span><br><span class="line"> * 用实际实例替换任何存根属性源。</span><br><span class="line"> * &lt;p&gt;Replace any stub property sources with actual instances.</span><br><span class="line"> * @see org.springframework.core.env.PropertySource.StubPropertySource</span><br><span class="line"> * @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources</span><br><span class="line"> */</span><br><span class="line">protected void initPropertySources() &#123;</span><br><span class="line">	// 对于子类：默认情况下不执行任何操作</span><br><span class="line">&#125;</span><br><span class="line">//这个方法主要做的事情就是把从servlet中得到的配置信息放到context的环境变量数据，这样spring就可以从context对应的key取得对应的变量</span><br><span class="line">//org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources</span><br><span class="line">public static void initServletPropertySources(MutablePropertySources sources,</span><br><span class="line">		@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) &#123;</span><br><span class="line"></span><br><span class="line">	Assert.notNull(sources, &quot;&apos;propertySources&apos; must not be null&quot;);</span><br><span class="line">	String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;</span><br><span class="line">	if (servletContext != null &amp;&amp; sources.contains(name) &amp;&amp; sources.get(name) instanceof StubPropertySource) &#123;</span><br><span class="line">		sources.replace(name, new ServletContextPropertySource(name, servletContext));</span><br><span class="line">	&#125;</span><br><span class="line">	name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;</span><br><span class="line">	if (servletConfig != null &amp;&amp; sources.contains(name) &amp;&amp; sources.get(name) instanceof StubPropertySource) &#123;</span><br><span class="line">		sources.replace(name, new ServletConfigPropertySource(name, servletConfig));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="validateRequiredProperties"><a href="#validateRequiredProperties" class="headerlink" title="validateRequiredProperties()"></a>validateRequiredProperties()</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">public void validateRequiredProperties() &#123;</span><br><span class="line">	MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();</span><br><span class="line">	for (String key : this.requiredProperties) &#123;</span><br><span class="line">		if (this.getProperty(key) == null) &#123;</span><br><span class="line">			ex.addMissingRequiredProperty(key);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	if (!ex.getMissingRequiredProperties().isEmpty()) &#123;</span><br><span class="line">		throw ex;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="obtainFreshBeanFactory"><a href="#obtainFreshBeanFactory" class="headerlink" title="obtainFreshBeanFactory()"></a>obtainFreshBeanFactory()</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * obtainFreshBeanFactory调用了refreshBeanFactory方法，AbstractRefreshableApplicationContext和</span><br><span class="line"> GenericApplicationContext 继承了AbstractApplicationContext类，实现了refreshBeanFactory()这个抽象</span><br><span class="line"> 方法。在两个类中，创建的beanFactory均是DefaultListableBeanFactory</span><br><span class="line"> */</span><br><span class="line">protected ConfigurableListableBeanFactory obtainFreshBeanFactory() &#123;</span><br><span class="line">	refreshBeanFactory();</span><br><span class="line">	ConfigurableListableBeanFactory beanFactory = getBeanFactory();</span><br><span class="line">	if (logger.isDebugEnabled()) &#123;</span><br><span class="line">		logger.debug(&quot;Bean factory for &quot; + getDisplayName() + &quot;: &quot; + beanFactory);</span><br><span class="line">	&#125;</span><br><span class="line">	return beanFactory;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="refreshBeanFactory"><a href="#refreshBeanFactory" class="headerlink" title="refreshBeanFactory()"></a>refreshBeanFactory()</h4><p>把xml文件中的bean定义被解析后，存放在DefaultListableBeanFactory的beanDefinitionMap中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">//此实现执行此上下文的底层bean工厂的实际刷新，关闭前一个bean工厂（如果有的话）并为上下文生命周期的下一阶段初始化一个新的bean工厂。</span><br><span class="line">//@see org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory</span><br><span class="line">@Override</span><br><span class="line">protected final void refreshBeanFactory() throws BeansException &#123;</span><br><span class="line">	//如果BeanFactory存在，销毁 ccontext管理的Bean，关闭掉BeanFactory</span><br><span class="line">	if (hasBeanFactory()) &#123;</span><br><span class="line">		destroyBeans();</span><br><span class="line">		closeBeanFactory();</span><br><span class="line">	&#125;</span><br><span class="line">	try &#123;</span><br><span class="line">		DefaultListableBeanFactory beanFactory = createBeanFactory();</span><br><span class="line">		beanFactory.setSerializationId(getId());</span><br><span class="line">		customizeBeanFactory(beanFactory);</span><br><span class="line">		loadBeanDefinitions(beanFactory);</span><br><span class="line">		synchronized (this.beanFactoryMonitor) &#123;</span><br><span class="line">			this.beanFactory = beanFactory;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	catch (IOException ex) &#123;</span><br><span class="line">		throw new ApplicationContextException(&quot;I/O error parsing bean definition source for &quot; + getDisplayName(), ex);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="createBeanFactory"><a href="#createBeanFactory" class="headerlink" title="createBeanFactory()"></a>createBeanFactory()</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">为context创建一个内部 beanFactory，当调用refresh()方法时调用此方法 ，默认创建一个DefaultListableBeanFactory</span><br><span class="line">将getInternalParentBeanFactory的父级作为内部的beanFactory</span><br><span class="line"> * @return the bean factory for this context</span><br><span class="line"> * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding</span><br><span class="line"> * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowEagerClassLoading</span><br><span class="line"> * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences</span><br><span class="line"> * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping</span><br><span class="line"> */</span><br><span class="line">protected DefaultListableBeanFactory createBeanFactory() &#123;</span><br><span class="line">	return new DefaultListableBeanFactory(getInternalParentBeanFactory());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="customizeBeanFactory"><a href="#customizeBeanFactory" class="headerlink" title="customizeBeanFactory()"></a>customizeBeanFactory()</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) &#123;</span><br><span class="line">	if (this.allowBeanDefinitionOverriding != null) &#123;</span><br><span class="line">		//allowBeanDefinitionOverriding表示是否允许注册一个同名的类来覆盖原有类(注意是类，不是实例)</span><br><span class="line">		beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);</span><br><span class="line">	&#125;</span><br><span class="line">	if (this.allowCircularReferences != null) &#123;</span><br><span class="line">		//allowCircularReferences表示是否运行多个类之间的循环引用</span><br><span class="line">		beanFactory.setAllowCircularReferences(this.allowCircularReferences);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="loadBeanDefinitions"><a href="#loadBeanDefinitions" class="headerlink" title="loadBeanDefinitions()"></a>loadBeanDefinitions()</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br></pre></td><td class="code"><pre><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * Load bean definitions into the given bean factory, typically through</span><br><span class="line">	 * delegating to one or more bean definition readers.</span><br><span class="line">	 * @param beanFactory the bean factory to load bean definitions into</span><br><span class="line">	 * @throws BeansException if parsing of the bean definitions failed</span><br><span class="line">	 * @throws IOException if loading of bean definition files failed</span><br><span class="line">	 * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader</span><br><span class="line">	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader</span><br><span class="line">	 */</span><br><span class="line">	protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)</span><br><span class="line">			throws BeansException, IOException;</span><br><span class="line">refreshBeanFactory()调用的loadBeanDefinitions(beanFactory)方法，在AbstractRefreshableApplicationContext类中只是一个接口，</span><br><span class="line">需要各个子类各自实现</span><br><span class="line">以AbstractXmlApplicationContext为例</span><br><span class="line">	/**</span><br><span class="line">	 * Load the bean definitions with the given XmlBeanDefinitionReader.</span><br><span class="line">	 * &lt;p&gt;The lifecycle of the bean factory is handled by the &#123;@link #refreshBeanFactory&#125;</span><br><span class="line">	 * method; hence this method is just supposed to load and/or register bean definitions.</span><br><span class="line">	 * @param reader the XmlBeanDefinitionReader to use</span><br><span class="line">	 * @throws BeansException in case of bean registration errors</span><br><span class="line">	 * @throws IOException if the required XML document isn&apos;t found</span><br><span class="line">	 * @see #refreshBeanFactory</span><br><span class="line">	 * @see #getConfigLocations</span><br><span class="line">	 * @see #getResources</span><br><span class="line">	 * @see #getResourcePatternResolver</span><br><span class="line">	 */</span><br><span class="line">	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException &#123;</span><br><span class="line">		Resource[] configResources = getConfigResources();</span><br><span class="line">		if (configResources != null) &#123;</span><br><span class="line">			reader.loadBeanDefinitions(configResources);</span><br><span class="line">		&#125;</span><br><span class="line">		String[] configLocations = getConfigLocations();</span><br><span class="line">		if (configLocations != null) &#123;</span><br><span class="line">			reader.loadBeanDefinitions(configLocations);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">getConfigResources()与getConfigLocations()方法代表了两种路径加载模式</span><br><span class="line">	//这种方式 使用了getConfigLocations()方式加载xml文件</span><br><span class="line">	public ClassPathXmlApplicationContext(</span><br><span class="line">			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)</span><br><span class="line">			throws BeansException &#123;</span><br><span class="line"></span><br><span class="line">		super(parent);</span><br><span class="line">		setConfigLocations(configLocations);</span><br><span class="line">		if (refresh) &#123;</span><br><span class="line">			refresh();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	//使用了getConfigResources()方式加载</span><br><span class="line">	public ClassPathXmlApplicationContext(String[] paths, Class&lt;?&gt; clazz, @Nullable ApplicationContext parent)</span><br><span class="line">			throws BeansException &#123;</span><br><span class="line"></span><br><span class="line">		super(parent);</span><br><span class="line">		Assert.notNull(paths, &quot;Path array must not be null&quot;);</span><br><span class="line">		Assert.notNull(clazz, &quot;Class argument must not be null&quot;);</span><br><span class="line">		this.configResources = new Resource[paths.length];</span><br><span class="line">		for (int i = 0; i &lt; paths.length; i++) &#123;</span><br><span class="line">			this.configResources[i] = new ClassPathResource(paths[i], clazz);</span><br><span class="line">		&#125;</span><br><span class="line">		refresh();</span><br><span class="line">	&#125;</span><br><span class="line">使用了不同的ClassPathXmlApplicationContext 构造方法，就会调用不同的方法来加载xml文件</span><br><span class="line">如果是使用了getConfigLocations方法，那么会调用XmlBeanDefinitionReader的父类AbstractBeanDefinitionReader的loadBeanDefinitions方法</span><br><span class="line">如果是使用了getConfigResources方法，那么会调用XmlBeanDefinitionReader的loadBeanDefinitions方法</span><br><span class="line">	/**</span><br><span class="line">	 * Load bean definitions from the specified XML file.</span><br><span class="line">	 * @param encodedResource the resource descriptor for the XML file,</span><br><span class="line">	 * allowing to specify an encoding to use for parsing the file</span><br><span class="line">	 * @return the number of bean definitions found</span><br><span class="line">	 * @throws BeanDefinitionStoreException in case of loading or parsing errors</span><br><span class="line">	 */</span><br><span class="line">	//使用getConfigResources方式</span><br><span class="line">	public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException &#123;</span><br><span class="line">		Assert.notNull(encodedResource, &quot;EncodedResource must not be null&quot;);</span><br><span class="line">		if (logger.isInfoEnabled()) &#123;</span><br><span class="line">			logger.info(&quot;Loading XML bean definitions from &quot; + encodedResource);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		Set&lt;EncodedResource&gt; currentResources = this.resourcesCurrentlyBeingLoaded.get();</span><br><span class="line">		if (currentResources == null) &#123;</span><br><span class="line">			currentResources = new HashSet&lt;&gt;(4);</span><br><span class="line">			this.resourcesCurrentlyBeingLoaded.set(currentResources);</span><br><span class="line">		&#125;</span><br><span class="line">		if (!currentResources.add(encodedResource)) &#123;</span><br><span class="line">			throw new BeanDefinitionStoreException(</span><br><span class="line">					&quot;Detected cyclic loading of &quot; + encodedResource + &quot; - check your import definitions!&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">		try &#123;</span><br><span class="line">			//调用InputStream对象</span><br><span class="line">			InputStream inputStream = encodedResource.getResource().getInputStream();</span><br><span class="line">			try &#123;</span><br><span class="line">				InputSource inputSource = new InputSource(inputStream);</span><br><span class="line">				if (encodedResource.getEncoding() != null) &#123;</span><br><span class="line">					inputSource.setEncoding(encodedResource.getEncoding());</span><br><span class="line">				&#125;</span><br><span class="line">				return doLoadBeanDefinitions(inputSource, encodedResource.getResource());</span><br><span class="line">			&#125;</span><br><span class="line">			finally &#123;</span><br><span class="line">				inputStream.close();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		catch (IOException ex) &#123;</span><br><span class="line">			throw new BeanDefinitionStoreException(</span><br><span class="line">					&quot;IOException parsing XML document from &quot; + encodedResource.getResource(), ex);</span><br><span class="line">		&#125;</span><br><span class="line">		finally &#123;</span><br><span class="line">			currentResources.remove(encodedResource);</span><br><span class="line">			if (currentResources.isEmpty()) &#123;</span><br><span class="line">				this.resourcesCurrentlyBeingLoaded.remove();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	/**</span><br><span class="line">	 * 实际从指定的XML文件加载bean定义。</span><br><span class="line">	 */</span><br><span class="line">	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)</span><br><span class="line">			throws BeanDefinitionStoreException &#123;</span><br><span class="line">		try &#123;</span><br><span class="line">			//解析xml</span><br><span class="line">			Document doc = doLoadDocument(inputSource, resource);</span><br><span class="line">			//注册</span><br><span class="line">			return registerBeanDefinitions(doc, resource);</span><br><span class="line">		&#125;</span><br><span class="line">		catch (BeanDefinitionStoreException ex) &#123;</span><br><span class="line">			throw ex;</span><br><span class="line">		&#125;</span><br><span class="line">		catch (SAXParseException ex) &#123;</span><br><span class="line">			throw new XmlBeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">					&quot;Line &quot; + ex.getLineNumber() + &quot; in XML document from &quot; + resource + &quot; is invalid&quot;, ex);</span><br><span class="line">		&#125;</span><br><span class="line">		catch (SAXException ex) &#123;</span><br><span class="line">			throw new XmlBeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">					&quot;XML document from &quot; + resource + &quot; is invalid&quot;, ex);</span><br><span class="line">		&#125;</span><br><span class="line">		catch (ParserConfigurationException ex) &#123;</span><br><span class="line">			throw new BeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">					&quot;Parser configuration exception parsing XML from &quot; + resource, ex);</span><br><span class="line">		&#125;</span><br><span class="line">		catch (IOException ex) &#123;</span><br><span class="line">			throw new BeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">					&quot;IOException parsing XML document from &quot; + resource, ex);</span><br><span class="line">		&#125;</span><br><span class="line">		catch (Throwable ex) &#123;</span><br><span class="line">			throw new BeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">					&quot;Unexpected exception parsing XML document from &quot; + resource, ex);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	/**</span><br><span class="line">	 * 注册给定DOM文档中包含的bean定义.</span><br><span class="line">	 * Called by &#123;@code loadBeanDefinitions&#125;.</span><br><span class="line">	 * &lt;p&gt;Creates a new instance of the parser class and invokes</span><br><span class="line">	 * &#123;@code registerBeanDefinitions&#125; on it.</span><br><span class="line">	 * @param doc the DOM document</span><br><span class="line">	 * @param resource the resource descriptor (for context information)</span><br><span class="line">	 * @return the number of bean definitions found</span><br><span class="line">	 * @throws BeanDefinitionStoreException in case of parsing errors</span><br><span class="line">	 * @see #loadBeanDefinitions</span><br><span class="line">	 * @see #setDocumentReaderClass</span><br><span class="line">	 * @see BeanDefinitionDocumentReader#registerBeanDefinitions</span><br><span class="line">	 */</span><br><span class="line">	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException &#123;</span><br><span class="line">		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();</span><br><span class="line">		int countBefore = getRegistry().getBeanDefinitionCount();</span><br><span class="line">		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));</span><br><span class="line">		return getRegistry().getBeanDefinitionCount() - countBefore;</span><br><span class="line">	&#125;</span><br><span class="line">	/**</span><br><span class="line">	 * Register each bean definition within the given root &#123;@code &lt;beans/&gt;&#125; element.</span><br><span class="line">	 */</span><br><span class="line">	protected void doRegisterBeanDefinitions(Element root) &#123;</span><br><span class="line">		// Any nested &lt;beans&gt; elements will cause recursion in this method. In</span><br><span class="line">		// order to propagate and preserve &lt;beans&gt; default-* attributes correctly,</span><br><span class="line">		// keep track of the current (parent) delegate, which may be null. Create</span><br><span class="line">		// the new (child) delegate with a reference to the parent for fallback purposes,</span><br><span class="line">		// then ultimately reset this.delegate back to its original (parent) reference.</span><br><span class="line">		// this behavior emulates a stack of delegates without actually necessitating one.</span><br><span class="line">		BeanDefinitionParserDelegate parent = this.delegate;</span><br><span class="line">		this.delegate = createDelegate(getReaderContext(), root, parent);</span><br><span class="line"></span><br><span class="line">		if (this.delegate.isDefaultNamespace(root)) &#123;</span><br><span class="line">			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);</span><br><span class="line">			if (StringUtils.hasText(profileSpec)) &#123;</span><br><span class="line">				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(</span><br><span class="line">						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);</span><br><span class="line">				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) &#123;</span><br><span class="line">					if (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(&quot;Skipped XML bean definition file due to specified profiles [&quot; + profileSpec +</span><br><span class="line">								&quot;] not matching: &quot; + getReaderContext().getResource());</span><br><span class="line">					&#125;</span><br><span class="line">					return;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		preProcessXml(root);</span><br><span class="line">		parseBeanDefinitions(root, this.delegate);</span><br><span class="line">		postProcessXml(root);</span><br><span class="line"></span><br><span class="line">		this.delegate = parent;</span><br><span class="line">	&#125;</span><br><span class="line">	/**</span><br><span class="line">	 * Parse the elements at the root level in the document:</span><br><span class="line">	 * &quot;import&quot;, &quot;alias&quot;, &quot;bean&quot;.</span><br><span class="line">	 * @param root the DOM root element of the document</span><br><span class="line">	 */</span><br><span class="line">	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) &#123;</span><br><span class="line">		if (delegate.isDefaultNamespace(root)) &#123;</span><br><span class="line">			NodeList nl = root.getChildNodes();</span><br><span class="line">			for (int i = 0; i &lt; nl.getLength(); i++) &#123;</span><br><span class="line">				Node node = nl.item(i);</span><br><span class="line">				if (node instanceof Element) &#123;</span><br><span class="line">					Element ele = (Element) node;</span><br><span class="line">					if (delegate.isDefaultNamespace(ele)) &#123;</span><br><span class="line">						parseDefaultElement(ele, delegate);</span><br><span class="line">					&#125;</span><br><span class="line">					else &#123;</span><br><span class="line">						delegate.parseCustomElement(ele);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		else &#123;</span><br><span class="line">			delegate.parseCustomElement(root);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) &#123;</span><br><span class="line">		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) &#123;</span><br><span class="line">			importBeanDefinitionResource(ele);</span><br><span class="line">		&#125;</span><br><span class="line">		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) &#123;</span><br><span class="line">			processAliasRegistration(ele);</span><br><span class="line">		&#125;</span><br><span class="line">		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) &#123;</span><br><span class="line">			processBeanDefinition(ele, delegate);</span><br><span class="line">		&#125;</span><br><span class="line">		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) &#123;</span><br><span class="line">			// recurse</span><br><span class="line">			doRegisterBeanDefinitions(ele);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * Process the given bean element, parsing the bean definition</span><br><span class="line">	 * and registering it with the registry.</span><br><span class="line">	 */</span><br><span class="line">	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) &#123;</span><br><span class="line">		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);</span><br><span class="line">		if (bdHolder != null) &#123;</span><br><span class="line">			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);</span><br><span class="line">			try &#123;</span><br><span class="line">				// 重点</span><br><span class="line">				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());</span><br><span class="line">			&#125;</span><br><span class="line">			catch (BeanDefinitionStoreException ex) &#123;</span><br><span class="line">				getReaderContext().error(&quot;Failed to register bean definition with name &apos;&quot; +</span><br><span class="line">						bdHolder.getBeanName() + &quot;&apos;&quot;, ele, ex);</span><br><span class="line">			&#125;</span><br><span class="line">			// Send registration event.</span><br><span class="line">			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	//最终调用了DefaultListableBeanFactory.registerBeanDefinition方法，把bean存入了beanDefinitionMap中</span><br><span class="line">	public static void registerBeanDefinition(</span><br><span class="line">			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)</span><br><span class="line">			throws BeanDefinitionStoreException &#123;</span><br><span class="line"></span><br><span class="line">		// Register bean definition under primary name.</span><br><span class="line">		String beanName = definitionHolder.getBeanName();</span><br><span class="line">		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());</span><br><span class="line"></span><br><span class="line">		// Register aliases for bean name, if any.</span><br><span class="line">		String[] aliases = definitionHolder.getAliases();</span><br><span class="line">		if (aliases != null) &#123;</span><br><span class="line">			for (String alias : aliases) &#123;</span><br><span class="line">				registry.registerAlias(beanName, alias);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<p><a href="https://img-blog.csdn.net/2018072621155141?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JvbGluZ19jYXZhbHJ5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" target="_blank" rel="noopener">详细的堆栈信息</a></p>
<h4 id="getBeanFactory"><a href="#getBeanFactory" class="headerlink" title="getBeanFactory()"></a>getBeanFactory()</h4><p>AbstractApplicationContext类中的getBeanFactory方法是由它的实现类来完成这个动作的<br>分别有AbstractRefreshableApplicationContext和GenericApplicationContext实现了这个方法</p>
<p>AbstractApplicationContext类在完成refreshBeanFactory方法<a href="#refreshBeanFactory("></a>)时，最后一步就是<br>设置(DefaultListableBeanFactory) beanFactory<br>AbstractApplicationContext中的getBeanFactory方法其实就是直接返回的beanFactory</p>
<h3 id="prepareBeanFactory"><a href="#prepareBeanFactory" class="headerlink" title="prepareBeanFactory()"></a>prepareBeanFactory()</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Configure the factory&apos;s standard context characteristics,</span><br><span class="line"> * such as the context&apos;s ClassLoader and post-processors.</span><br><span class="line"> * @param beanFactory the BeanFactory to configure</span><br><span class="line"> */</span><br><span class="line">protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) &#123;</span><br><span class="line">	//设置类加载器</span><br><span class="line">	beanFactory.setBeanClassLoader(getClassLoader());</span><br><span class="line">	//设置解析器，用于解析bean的定义中出现的Spel表达式表达式</span><br><span class="line">	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));</span><br><span class="line">	//设置一个注册接口，该接口只有一个方法registerCustomEditors，用来设置自定义的转换器</span><br><span class="line">	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));</span><br><span class="line"></span><br><span class="line">	//部署一个bean的后置处理器ApplicationContextAwareProcessor，用于将spring的环境信息注入到实例化的bean之中</span><br><span class="line">	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));</span><br><span class="line">	//bean在初始化的时候，如果有属性的类型为以下类型，则该属性不会被依赖注入</span><br><span class="line">	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);</span><br><span class="line">	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);</span><br><span class="line">	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);</span><br><span class="line">	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);</span><br><span class="line">	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);</span><br><span class="line">	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);</span><br><span class="line"></span><br><span class="line">	// BeanFactory interface not registered as resolvable type in a plain factory.</span><br><span class="line">	// MessageSource registered (and found for autowiring) as a bean.</span><br><span class="line">	//bean如果有个属性的类型为BeanFactory.class，那么该属性会被设置为beanFactory</span><br><span class="line">	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);</span><br><span class="line">	beanFactory.registerResolvableDependency(ResourceLoader.class, this);</span><br><span class="line">	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);</span><br><span class="line">	beanFactory.registerResolvableDependency(ApplicationContext.class, this);</span><br><span class="line"></span><br><span class="line">	// Register early post-processor for detecting inner beans as ApplicationListeners.</span><br><span class="line">	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));</span><br><span class="line"></span><br><span class="line">	// Detect a LoadTimeWeaver and prepare for weaving, if found.</span><br><span class="line">	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) &#123;</span><br><span class="line">		//添加一个bean的后置处理器ApplicationContextAwareProcessor，用于AOP静态代理相关的处理</span><br><span class="line">		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));</span><br><span class="line">		// Set a temporary ClassLoader for type matching.</span><br><span class="line">		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	// Register default environment beans.</span><br><span class="line">	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) &#123;</span><br><span class="line">		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());</span><br><span class="line">	&#125;</span><br><span class="line">	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) &#123;</span><br><span class="line">		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());</span><br><span class="line">	&#125;</span><br><span class="line">	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) &#123;</span><br><span class="line">		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="postProcessBeanFactory"><a href="#postProcessBeanFactory" class="headerlink" title="postProcessBeanFactory()"></a>postProcessBeanFactory()</h3><p>postProcessBeanFactory方法在AbstractApplicationContext只是一个接口，由它的子类来完成具体的实现<br>以AbstractRefreshableWebApplicationContext为例，<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) &#123;</span><br><span class="line">	beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));</span><br><span class="line">	beanFactory.ignoreDependencyInterface(ServletContextAware.class);</span><br><span class="line">	beanFactory.ignoreDependencyInterface(ServletConfigAware.class);</span><br><span class="line"></span><br><span class="line">	WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);</span><br><span class="line">	WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="invokeBeanFactoryPostProcessors"><a href="#invokeBeanFactoryPostProcessors" class="headerlink" title="invokeBeanFactoryPostProcessors()"></a>invokeBeanFactoryPostProcessors()</h3><h3 id="registerBeanPostProcessors"><a href="#registerBeanPostProcessors" class="headerlink" title="registerBeanPostProcessors()"></a>registerBeanPostProcessors()</h3><h3 id="initMessageSource"><a href="#initMessageSource" class="headerlink" title="initMessageSource()"></a>initMessageSource()</h3><h3 id="initApplicationEventMulticaster"><a href="#initApplicationEventMulticaster" class="headerlink" title="initApplicationEventMulticaster()"></a>initApplicationEventMulticaster()</h3><h3 id="onRefresh"><a href="#onRefresh" class="headerlink" title="onRefresh()"></a>onRefresh()</h3><h3 id="registerListeners"><a href="#registerListeners" class="headerlink" title="registerListeners()"></a>registerListeners()</h3><h3 id="finishBeanFactoryInitialization"><a href="#finishBeanFactoryInitialization" class="headerlink" title="finishBeanFactoryInitialization()"></a>finishBeanFactoryInitialization()</h3><h3 id="finishRefresh"><a href="#finishRefresh" class="headerlink" title="finishRefresh()"></a>finishRefresh()</h3>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/10/14/MySQL/" rel="next" title="MySQL">
                <i class="fa fa-chevron-left"></i> MySQL
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/11/18/SpringMVC/" rel="prev" title="SpringMVC">
                SpringMVC <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiehuan</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">27</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#refresh"><span class="nav-number">1.</span> <span class="nav-text">refresh()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#prepareRefresh"><span class="nav-number">1.1.</span> <span class="nav-text">prepareRefresh()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#initPropertySources"><span class="nav-number">1.1.1.</span> <span class="nav-text">initPropertySources()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#validateRequiredProperties"><span class="nav-number">1.1.2.</span> <span class="nav-text">validateRequiredProperties()</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#obtainFreshBeanFactory"><span class="nav-number">1.2.</span> <span class="nav-text">obtainFreshBeanFactory()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#refreshBeanFactory"><span class="nav-number">1.2.1.</span> <span class="nav-text">refreshBeanFactory()</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#createBeanFactory"><span class="nav-number">1.2.1.1.</span> <span class="nav-text">createBeanFactory()</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#customizeBeanFactory"><span class="nav-number">1.2.1.2.</span> <span class="nav-text">customizeBeanFactory()</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#loadBeanDefinitions"><span class="nav-number">1.2.1.3.</span> <span class="nav-text">loadBeanDefinitions()</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#getBeanFactory"><span class="nav-number">1.2.2.</span> <span class="nav-text">getBeanFactory()</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#prepareBeanFactory"><span class="nav-number">1.3.</span> <span class="nav-text">prepareBeanFactory()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#postProcessBeanFactory"><span class="nav-number">1.4.</span> <span class="nav-text">postProcessBeanFactory()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#invokeBeanFactoryPostProcessors"><span class="nav-number">1.5.</span> <span class="nav-text">invokeBeanFactoryPostProcessors()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#registerBeanPostProcessors"><span class="nav-number">1.6.</span> <span class="nav-text">registerBeanPostProcessors()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#initMessageSource"><span class="nav-number">1.7.</span> <span class="nav-text">initMessageSource()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#initApplicationEventMulticaster"><span class="nav-number">1.8.</span> <span class="nav-text">initApplicationEventMulticaster()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#onRefresh"><span class="nav-number">1.9.</span> <span class="nav-text">onRefresh()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#registerListeners"><span class="nav-number">1.10.</span> <span class="nav-text">registerListeners()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#finishBeanFactoryInitialization"><span class="nav-number">1.11.</span> <span class="nav-text">finishBeanFactoryInitialization()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#finishRefresh"><span class="nav-number">1.12.</span> <span class="nav-text">finishRefresh()</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiehuan</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







       <p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
